﻿using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Ini
{
    public class IniFile
    {
        public string path;

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        public IniFile(string IniPath)
        {
            path = IniPath;
        }

        public void IniWriteValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, this.path);
        }

        public string IniReadValue(string section, string key, string def)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, (def != null ? def : string.Empty), temp, 255, this.path);
            return temp.ToString();
        }

        public void IniWritevalue(string section, string key, int value)
        {
            IniWriteValue(section, key, value.ToString());
        }

        public int IniReadvalue(string section, string key, int? def)
        {
            string s = IniReadValue(section, key, (def != null ? def.ToString() : null));
            int i = 0;
            if (int.TryParse(s, out i))
                return i;
            else
                throw new IniFileException("Tried to retrieve invalid value type from ini.");
        }
    }

    public class IniFileException : Exception
    {
        public IniFileException(string Message)
            : base(Message)
        {

        }
    }
}